package com.wsc.crawler.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.apache.log4j.Logger;

/*
 * This class checks the reachability of server,
 * 
 *  And checks whether a port is Up
 */

public class CheckHost {
	static boolean isreachable=false;
	static InetAddress host=null;
	private static Logger log=Logger.getLogger(CheckHost.class.getName());
	
	/*
	 *  accepts host name as string and checks whether a host is reachable
	 */
	
	public static boolean isReachableTo(String hostname){
		try {
//	log.info("pinging the host "+hostname+".");
			//make the string as inetaddress object.
		host = InetAddress.getByName(hostname);
		isreachable=host.isReachable(10000);

	} catch (UnknownHostException e) {
	log.warn("Host ("+hostname+") is unknown MESG="+e.getMessage());
	} catch (IOException e) {
    log.warn("IOException thrown in ", e);
	}
		
	if(isreachable){
//		log.info("pinging the host "+hostname+" is successfull.");	
		return true;
	}else{
		log.debug("Host ("+hostname+") is unreachable");
		return false;
		}
	}

	/*
	 * accepts host name as InetAddress and checks the reachability of the host. 
	 */
	public static boolean isReachableTo(InetAddress host){
	try {
		isreachable=host.isReachable(10000);
	} catch (UnknownHostException e) {
		log.warn("Host is unknown. MESG="+e.getMessage());
	} catch (IOException e) {
		 log.warn("IOException thrown in MESG="+e.getMessage());
	}
	if(isreachable){
		log.debug("Host ("+host.getHostName()+") is reachable.");	
		return true;
	}else{
		log.debug("Host ("+host.getHostName()+") is reachable.");
		return false;
	}
	
	}
	
/*
 *  isPortOpen method checks for whether a port is open or not,
 *  this can be used to check frontier server and index server, whether they are started or not.
 * 	
 */
 
	public static boolean isPortOpen(HttpHost host){
		Socket socket = null;
		try {
		//	log.info("Checking whether "+host.toString()+" is reachable.");
			socket = new Socket(host.getHostName(),host.getPort());
			socket.close();
//			log.info("the host "+host.toString()+" is reachable.");
			return true;
		} catch (UnknownHostException e) {
			log.info("Host ("+host.toURI()+") is unknown MESG="+e.getMessage());
			return false;
		} catch (IOException e) {
			log.info("iOException is thrown while connecting ("+host.toURI()+") MESG="+e.getMessage());
			return false;
		}finally{
			try {
				if(socket != null)
					socket.close();
			} catch (IOException e) {
				log.warn("Exception occur while closing socket. MESG="+e.getMessage()); 
			}
		}
        
	}
	 	 
}
